import styles from './index.module.scss'
import { useEffect, useRef, useState, KeyboardEvent } from 'react'
import { useInitialState } from '@/hooks/useInitialState'
import { getProfileAsync } from '@/store/index'
import Icon from '@/components/icon'
import { NavBar, Toast, Input } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { io, type Socket } from 'socket.io-client'
import { useAppSelector } from '@/store/index'

type MessageInfoItem = { type: 'robot' | 'user'; text: string }

export default function Chat() {
  const navigate = useNavigate()
  const { authInfo } = useAppSelector((state) => state.loginSlice)
  const { profile } = useInitialState(getProfileAsync, 'loginSlice')

  const socketRef = useRef<Socket | null>(null)
  const chatListRef = useRef<HTMLDivElement>(null)
  // 创建io实例和连接
  function createIoClient() {
    const socket = io('http://toutiao.itheima.net', {
      transports: ['websocket'],
      query: {
        token: authInfo.token
      }
    })
    socket.on('connect', () => {
      Toast.show('建立连接成功')
    })
    socket.on('message', (data) => {
      console.log('>>>收到 socket.io 消息', data)
      // 向聊天记录中添加机器人回复的消息
      setMessageList((messageList) => [...messageList, { type: 'robot', text: data.msg }])
    })
    socketRef.current = socket
  }
  useEffect(() => {
    if (!socketRef.current) createIoClient()
    return () => {
      socketRef.current && socketRef.current.close()
    }
  }, [])

  // 信息列表
  const [messageList, setMessageList] = useState<MessageInfoItem[]>([])
  // 输入框信息
  const [message, setMessage] = useState('')
  // 发送信息
  function onSendMessage(e: KeyboardEvent<HTMLInputElement>) {
    if (e.code === 'Enter') {
      // 通过 socket.io 客户端向服务端发送消息
      socketRef.current!.emit('message', {
        msg: message,
        timestamp: Date.now()
      })
      // 向聊天记录中添加当前发送的消息
      setMessageList((messageList) => [...messageList, { type: 'user', text: message }])
      // 发送后清空输入框
      setMessage('')
    }
  }
  // 监听聊天数据的变化，改变聊天容器元素的 scrollTop 值让页面滚到最底部
  useEffect(() => {
    const current = chatListRef.current!
    current.scrollTop = current.scrollHeight
  }, [messageList])
  return (
    <>
      <div className={styles.root}>
        {/* 顶部导航栏 */}
        <NavBar className="fixed-header" onBack={() => navigate(-1)}>
          小智同学
        </NavBar>
        {/* 聊天记录列表 */}
        <div className="chat-list" ref={chatListRef}>
          {messageList.map((msg, index) => {
            // 机器人的消息
            if (msg.type === 'robot') {
              return (
                <div className="chat-item" key={index}>
                  <Icon type="iconbtn_xiaozhitongxue" />
                  <div className="message">{msg.text}</div>
                </div>
              )
            }
            // 用户的消息
            else {
              return (
                <div className="chat-item user" key={index}>
                  <img src={profile.photo} alt="" />
                  <div className="message">{msg.text}</div>
                </div>
              )
            }
          })}
        </div>
        {/* 底部消息输入框 */}
        <div className="input-footer">
          <Input
            className="no-border input"
            placeholder="请描述您的问题"
            value={message}
            onChange={(e) => setMessage(e)}
            onKeyDown={onSendMessage}
          />
          <Icon type="iconbianji" />
        </div>
      </div>
    </>
  )
}
